<template>
    <div>
        <h2>订单结算页面</h2>

      <!--折扣    -->
      <el-card style="margin-top: 20px">
        <h3 style="text-align: left;border-bottom:1px solid gainsboro;padding-bottom: 5px">当前订单可用折扣(自动计算每个商品所适应最高折扣)</h3>
        <el-table :data="discountList"  border stripe>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="id" prop="id"></el-table-column>
          <el-table-column label="折扣名" prop="name"></el-table-column>
          <el-table-column label="享受折扣商品及其折扣率" prop="list">
            <template slot-scope="scope">
              <b v-for="item in scope.row.list" v-html="item.commodityname+'&nbsp;&nbsp;&nbsp;'+item.rate+'<p>'"><hr/>
              </b>
            </template>
          </el-table-column>
          <el-table-column label="折扣金额" prop="reduceNum"></el-table-column>
          <el-table-column label="是否适用" prop="status">
            <template slot-scope="scope">
              <el-tooltip placement="top">
                <el-switch
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeStatus1(scope.row)"
                >
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>

        </el-table>
      </el-card>
      <!--优惠券    -->
      <el-card style="margin-top: 20px">
        <h3 style="text-align: left;border-bottom:1px solid gainsboro;padding-bottom: 5px">该用户适用优惠券</h3>
        <el-table :data="couponList"  border stripe>

          <el-table-column type="index"></el-table-column>
          <el-table-column label="优惠券名称" prop="couponname"></el-table-column>
          <el-table-column label="优惠券类型" prop="couponType.coupontypename"></el-table-column>

          <el-table-column label="优惠额度" prop="reduce"></el-table-column>
          <el-table-column label="折扣率" prop="rate"></el-table-column>
          <el-table-column label="适用阈值" prop="threshold"></el-table-column>
          <el-table-column label="是否适用" prop="status">
            <template slot-scope="scope">
              <el-tooltip placement="top">
                <el-switch
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeStatus(scope.row)"
                    :disabled = "selectEnable(scope.row)"
                >
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!--包邮    -->
      <el-card style="margin-top: 20px">
        <h3 style="text-align: left;border-bottom:1px solid gainsboro;padding-bottom: 5px">当前使用包邮规则</h3>
        <el-table :data="freeShipNow"  border stripe>

          <el-table-column type="index"></el-table-column>
          <el-table-column label="包邮规则名称" prop="name"></el-table-column>
          <el-table-column label="规则说明" prop="introduce"></el-table-column>
          <el-table-column label="包邮阈值" prop="threshold"></el-table-column>
          <el-table-column label="参与计算包邮总价" prop="priceAll"></el-table-column>
        </el-table>
        <h3 style="text-align: left;border-bottom:1px solid gainsboro;padding-bottom: 5px">
          <b>是否包邮:</b>
          <b v-show="freeShip">包邮</b>
          <b v-show="!freeShip">不包邮</b>
        </h3>

      </el-card>
      <!--满减   -->
      <el-card style="margin-top: 20px">
        <h3 style="text-align: left;border-bottom:1px solid gainsboro;padding-bottom: 5px">当前适用满减</h3>
        <el-table :data="reduceList"  border stripe>

          <el-table-column type="index"></el-table-column>
          <el-table-column label="满减规则名称" prop="name"></el-table-column>
          <el-table-column label="规则说明" prop="introduce"></el-table-column>
          <el-table-column label="满减阈值" prop="threshold"></el-table-column>
          <el-table-column label="满减值" prop="reduce"></el-table-column>
          <el-table-column label="是否适用" prop="status">
            <template slot-scope="scope">
              <el-tooltip placement="top">
                <el-switch
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeStatus2(scope.row)"
                >
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

      </el-card>
      <!--满赠商品   -->
      <el-card style="margin-top: 20px">
        <h3 style="text-align: left;border-bottom:1px solid gainsboro;padding-bottom: 5px">当前会员等级满赠
          <b>您的会员等级是</b>
          <b v-text="svip.name"></b>
        </h3>
        <el-table :data="presentList"  border stripe>

          <el-table-column type="index"></el-table-column>
          <el-table-column label="满减规则名称" prop="name"></el-table-column>
          <el-table-column label="满赠阈值" prop="threshold"></el-table-column>

          <el-table-column label="赠送商品" prop="list1">
            <template slot-scope="scope">
              <b v-for="item in scope.row.list1" v-html="item.commodityname+'<p>'"><hr/>
              </b>
            </template>
          </el-table-column>
          <el-table-column label="是否适用" prop="status0">
            <template slot-scope="scope">
              <el-tooltip placement="top">
                <el-switch
                    v-model="scope.row.status0"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeStatus3(scope.row)"
                    :disabled = "selectEnable(scope.row)"
                >
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

      </el-card>
      <!--价格详情   -->
      <el-card style="margin-top: 20px">
        <h3 style="text-align: left;border-bottom:1px solid gainsboro;padding-bottom: 5px">折扣叠加后价格计算
          <b>折前价格：</b>
          <b v-text="price"></b>

          <b>&nbsp;&nbsp;&nbsp;折后价格：</b>
          <b v-text="truePrice"></b>
          <div style="float: right;margin-right: 30px;">
            <el-button type="primary" size="mini" @click="commitOrder">去支付</el-button>
          </div>
        </h3>


      </el-card>
    </div>
</template>

<script>
    export default {

      data() {
        return {
          //商品id集合
          commodityIds:[

          ],
          //用户id
          userId:'',
          //直播id
          liveId:'',
          //该用户id可用的优惠券
          couponList:[],
          //查询当前时间段可以使用的折扣
          discountList:[],
          //获取满减
          reduceList:[],
          //获取当前用户的svip等级
          svip:'',
          //获取当前vip等级所适用权益
          equityList:'',
          //获取当前用户 所在vip等级的 适应满赠
          presentList:'',
          //查看当前包邮规则
          freeShipNow:'',
          //获取当前用户积分
          integral:'',
          //获取当前订单总价格(折前）
          price:'2026.4',
/*          price:'800',*/
          //计算完所有优惠 折扣等的价格
          truePrice:'2026.4',
          resultList:[],
          //是否包邮
          freeShip:false,
          //包邮商品总价 折前
          priceAll:'',
          //
          commodityList:[],

          //用户选择的满赠商品
          presentCommodityList:[],


          //生成订单相关
          discountId:0,//选中的折扣id
          couponId:0,//选中的优惠券id
          reduceId:0,//选中的满减id
          presentId:0,//选中的满赠id
          orderId:0,
          //订单
          order:{
            userid:'',
            orderStatus:3,
            paymethod:1,
            source:1,
            priceold:'',
            pricenew:'',
            isCommodity:1,
            couponid:''
          },
          //订单详情
          orderDetail:{
            orderId:'',
            presentCommodityVoList:[],
          },

          //支付宝沙箱相关
          orderForm:{
            orderNum:"",
            orderPrice:0,
            orderName:"",
            productDescription:""
          },
        }
      },

      methods:{


        commitOrder(){
          //1.折扣data表 2.优惠券data表 3.满赠-订单表 4.订单表 5.订单详情表
          let userId = this.userId;

          console.log(this.discountId+'---'+this.couponId);
          console.log(this.reduceId+'---'+this.presentId);
          //1.折扣data表
          let url1 = "discount/useDiscount";
          this.$axios.get(url1,{
            params:{
              userId:this.userId,
              discountId:this.discountId
            }
          }).then(res=> {
            if (res.data.code == 200) {


            }else {
              this.$message({
                type: "error",
                message: res.data.msg,
                duration: 1000
              })
            }
          })
          //2.优惠券data表
          let url2 = "coupon/useCoupon";
          this.$axios.get(url2,{
            params:{
              userId:this.userId,
              couponId:this.couponId
            }
          }).then(res=> {
            if (res.data.code == 200) {
            }else {
              this.$message({
                type: "error",
                message: res.data.msg,
                duration: 1000
              })
            }
          })
          //3.满赠-订单表
          let url3 = "present/addNew";
          this.$axios.get(url3,{
            params:{
              presentId:this.presentId,
              orderId:this.orderId
            }
          }).then(res=> {
            if (res.data.code == 200) {
            }else {
              this.$message({
                type: "error",
                message: res.data.msg,
                duration: 1000
              })
            }
          })
          //4.订单表

          let url4 = "pay/addOrder";
          this.order.userid = this.userId;
          this.order.priceold = this.price;
          this.order.pricenew = this.truePrice;
          if (this.couponId != 0){
            this.order.couponid = this.couponId;
          }

          this.$axios.post(url4,this.order).then(res=>{
            if (res.data.code == 200){
              //生成完成 转到支付页面
              let order0 = res.data.data;
              this.orderId = order0.id;
              let orderId0 = order0.id;

              //5.订单详情表
              let url5 = "pay/addOrderDetailsVo";
              this.orderDetail.orderId = orderId0;
              this.orderDetail.presentCommodityVoList = this.commodityIds
              this.$axios.post(url5,this.orderDetail).then(res=>{
                if (res.data.code == 200){

                  //6.资产表
                  let revenueRecordVo = {
                    revenueType:'收入',
                    amountNum:this.truePrice,
                    billType:'订单收入',
                    billSummary:'测试用描述',
                    orderNumber:order0.orderNum
                  }

                  let url6 = "pay/addRevenueRecord"
                  this.$axios.post(url6,revenueRecordVo).then(res=>{
                    if (res.data.code == 200) {

                      let url7 = "pay/editGrowthValue";
                      let growth = ((this.truePrice/10)+200+50).toFixed(0);
                      let growthValueVo = {
                        uid:this.userId,
                        growthValue:growth,
                        beiZhu:'测试'
                      }
                      this.$axios.put(url7,growthValueVo).then(res=>{
                        if (res.data.code == 200) {

                          let url8 = "pay/editIntegral";
                          let integral = this.truePrice.toFixed(0);
                          let changeIntegralVo = {
                            uid:this.userId,
                            integral:integral,
                            beiZhu:'测试'
                          }
                          this.$axios.put(url8,changeIntegralVo).then(res=>{
                            if (res.data.code == 200) {



                              let url9 = "pay/alipay";
                              this.orderForm.orderNum = order0.orderNum;
                              this.orderForm.orderPrice = this.truePrice.toFixed(2);
                              this.orderForm.orderName = "测试购买商品";
                              this.orderForm.productDescription = "购买商品测试";

                              this.$axios.put(url9,this.orderForm).then(res=>{

                                if (res.data.code == 200){
                                  const divForm = document.getElementsByTagName("div");
                                  if (divForm.length) {
                                    document.body.removeChild(divForm[0]);
                                  }
                                  const div = document.createElement("div");
                                  div.innerHTML = res.data.data; // data就是接口返回的form 表单字符串
                                  document.body.appendChild(div);
                                  window.close();//本窗口页面关闭
                                  document.forms[0].setAttribute("target", "_blank"); // 新开窗口跳转
                                  document.forms[0].submit();

                                }else {
                                  this.$message({
                                    type:"error",
                                    message:res.data.msg,
                                    duration:1000
                                  })
                                }

                              });





                            }else {
                              this.$message({
                                type: "error",
                                message: res.data.msg,
                                duration: 1000
                              })
                            }
                          })


                        }else{
                          this.$message({
                            type: "error",
                            message: res.data.msg,
                            duration: 1000
                          })
                        }
                      })

                    }else{
                      this.$message({
                        type: "error",
                        message: res.data.msg,
                        duration: 1000
                      })
                    }
                  })

                }else {
                  this.$message({
                    type: "error",
                    message: res.data.msg,
                    duration: 1000
                  })
                }
              })


            }else {
              this.$message({
                type: "error",
                message: res.data.msg,
                duration: 1000
              })
            }
          })







        },

        //计算真实价格
        getTruePrice(){
          let price = this.price;
          this.presentCommodityList=[];
          this.discountId = 0;
          this.couponId = 0;
          this.reduceId = 0;
          this.presentId = 0;

          this.discountList.forEach(value => {
            if (value.status == 1){
              price = (price - value.reduceNum).toFixed(2);
              this.discountId = value.id;
            }
          })

          this.couponList.forEach(value => {
            if (value.status == 1){

              if (value.couponType.id == 1){
                //满减卷
                price = price - value.reduce;
              }else{
                price = (price * value.rate).toFixed(2);
              }
              this.couponId = value.id;
            }
          })

          this.reduceList.forEach(value => {
            if (value.status == 1){
              price = price - value.reduce.toFixed(2);
              this.reduceId = value.id;
            }
          })

          this.presentList.forEach(value => {
            if (value.status0 == 1){
              this.presentCommodityList = value.list1;
              this.presentId = value.id;
            }
          })
          this.truePrice = price;
        },

        //满赠相关
        changeStatus3(obj) {
          let id = obj.id;
          this.presentList.forEach(value => {
            if (value.id != id){
              value.status0 = 0;
            }
          })
          this.getTruePrice();
        },
        //获取用户svip等级 以及积分
        getSvip(){
          let url = "svip/getSvip";
          this.$axios.get(url,{
            params:{
              userId:this.userId,
            }
          }).then(res=> {
            if (res.data.code == 200) {
              this.integral = res.data.data.integral;
              this.svip = res.data.data.svip;
              this.getPresentList();
            }else {
              this.$message({
                type: "error",
                message: res.data.msg,
                duration: 1000
              })
            }
          })
        },
        //根据svip等级获取其满赠
        getPresentList() {

          let url = "present/getPresent";
          this.$axios.get(url,{
            params:{
              svipId:this.svip.id
            }
          }).then(res=> {
            if (res.data.code == 200) {
              this.presentList = res.data.data;
            }else {
              this.$message({
                type: "error",
                message: res.data.msg,
                duration: 1000
              })
            }
          })
        },


        //选择满减相关
        changeStatus2(obj) {
          let id = obj.id;
          this.reduceList.forEach(value => {
            if (value.id != id){
              value.status = 0;
            }
          })
          this.getTruePrice();
        },
        getReduce(){
          let url = "reduce/getNow"
          this.$axios.get(url).then(res=> {
            if (res.data.code == 200) {
              this.reduceList = res.data.data;
            }else {
              this.$message({
                type: "error",
                message: res.data.msg,
                duration: 1000
              })
            }
          })
        },
        getFreeShip(){
          let url = "freeship/getNow"
          this.$axios.get(url).then(res=>{
            if (res.data.code == 200){
              this.freeShipNow = res.data.data;
              //进行是否包邮的判断
              if(this.freeShipNow[0].effective == 1){
                //作用域全场
                this.priceAll = this.price;
                if (this.price > this.freeShipNow[0].threshold && this.freeShipNow[0].id != 1){
                  //包邮
                  this.freeShip = true;
                }
                //其余条件不包邮

              }else{
                //作用域非全场
                //计算包邮商品价格
                let priceAll = 0;
                this.freeShipNow[0].list.forEach(value =>{

                  this.commodityIds.forEach(value1 => {
                    if (value.id == value1.id){
                      priceAll += value.commodityprice * value1.num;
                    }
                  })
                })
                this.priceAll = priceAll;

                if (priceAll > this.freeShipNow[0].threshold){
                  this.freeShip = true;
                }
              }

              this.freeShipNow[0].priceAll = this.priceAll;


            }else{
              this.$message({
                type:"error",
                message:res.data.msg,
                duration:1000
              })
            }
          })
        },
        //选择折扣相关
        changeStatus1(obj) {
          let id = obj.id;
          this.discountList.forEach(value => {
            if (value.id != id){
              value.status = 0;
            }
          })

          this.getTruePrice();
        },
        getMaxDiscount(){

          this.discountList.forEach(value =>{
            //当前折扣当前订单优惠金额
            let reduceNum = 0;

            value.list.forEach(value1 => {

              this.commodityIds.forEach(value2 => {
                if (value2.id == value1.id){
                  reduceNum = reduceNum + value1.commodityprice*(1-value1.rate)*value2.num
                }
              })
            })
            value.reduceNum = reduceNum.toFixed(2);
          })
        },
        selectEnable(row) { //判断是否可用这张优惠券
          if (row.threshold > this.price) { // 禁用
            return true;
          } else {
            return false;
          }
        },
        changeStatus(obj) {
          let id = obj.id;
          this.couponList.forEach(value => {
            if (value.id != id){
              value.status = 0;
            }
          })

          this.getTruePrice();
        },
        //获取折扣方法
        getDiscountList(){
          let url = "discount/findNow";
          let commodityIds = [];
          this.commodityIds.forEach(value => {
            commodityIds.push(value.id)
          });
          let params = {ids:commodityIds};
          this.$axios({
            url:url,
            method:'get',
            params:params,
            paramsSerializer:params=>{
              return this.$qs.stringify(params,{indices:false})
            }
          }).then(res=> {
            if (res.data.code == 200) {
              this.discountList = res.data.data;
              this.getMaxDiscount();
            } else {
              this.$message({
                type: "error",
                message: res.data.msg,
                duration: 1000
              })
            }
          })
        },


        //获取优惠券list方法
        getConponList(){
          let url = "coupon/findByUserId";
          this.$axios.get(url,{
            params:{
              id:this.userId,
            }
          }).then(res=>{
            if (res.data.code == 200){
              this.couponList = res.data.data;
            }else{
              this.$message({
                type:"error",
                message:res.data.msg,
                duration:1000
              })
            }
          })
        },
        reloadData(){
          this.getConponList();
          this.getDiscountList();
          this.getFreeShip();
          this.getReduce();
          this.getSvip();
        }

      },
      created() {
        //获取用户
        this.userId = JSON.parse(sessionStorage.getItem("user")).id;
        //获取直播id
        this.liveId = this.$route.query.liveId;
        //获取商品集合
        this.commodityIds = this.$route.query.Commodity;
        console.log(this.commodityIds);

        //获取总价
        let price = 0;
        this.commodityIds.forEach(value => {
          price = price + (value.num * value.commodityprice);
        })
        this.price = price.toFixed(2);
        this.truePrice = this.price;
        this.reloadData();


      }
    }
</script>

<style scoped>

</style>